<template>
	<view class="snowy-form">
		<uni-forms ref="formRef" :model="formData" :rules="rules" validate-trigger="blur" label-position="top" labelWidth="auto">
      <!-- 添加头像表单项 -->
      <!--      <uni-forms-item label="头像" name="avatar">-->
      <!--        <view class="avatar-container">-->
      <!--          <view class="avatar-wrapper" @click="chooseAvatar">-->
      <!--            <image-->
      <!--                :src="formData.avatar || '/static/logo.png'"-->
      <!--                mode="aspectFill"-->
      <!--                class="avatar-image"-->
      <!--            ></image>-->
      <!--            <view class="avatar-mask">-->
      <!--              <uni-icons type="camera" size="24" color="#fff"></uni-icons>-->
      <!--              <text class="avatar-text">点击更换</text>-->
      <!--            </view>-->
      <!--          </view>-->
      <!--        </view>-->
      <!--      </uni-forms-item>-->
      <uni-forms-item label="一卡通号码" name="name" required :rules="[{ required: true, errorMessage: '请输入一卡通号码' }]">
        <uni-easyinput v-model="formData.account" :disabled="true"></uni-easyinput>
      </uni-forms-item>
			<uni-forms-item label="姓名" name="name" required :rules="[{ required: true, errorMessage: '请输入账号' }]">
				<uni-easyinput v-model="formData.name" placeholder="请输入姓名"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item label="手机号码" name="phone">
				<uni-easyinput v-model="formData.phone" placeholder="请输入手机号码" :disabled="true"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item label="昵称" name="nickname">
				<uni-easyinput v-model="formData.nickname" placeholder="请输入昵称"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item label="性别" name="gender">
				<uni-data-checkbox v-model="formData.gender" :localdata="genderOptions" />
			</uni-forms-item>
			<uni-forms-item label="生日" name="birthday">
				<uni-datetime-picker type="date" return-type="string" format="YYYY-MM-DD" v-model="formData.birthday" />
			</uni-forms-item>
			<uni-forms-item label="邮箱" name="email">
				<uni-easyinput v-model="formData.email" placeholder="请输入邮箱"></uni-easyinput>
			</uni-forms-item>
		</uni-forms>
		<tui-button margin="50rpx 0" :preventClick="true" :shadow="true" @click="submit">保存</tui-button>
	</view>
</template>
<script setup>
	import userCenterApi from '@/api/sys/user-center-api'
  import fileApi from '@/api/dev/file-api'
	import { reactive, ref } from "vue"
	import { onLoad, onReady } from '@dcloudio/uni-app'
	import store from '@/store/index.js'
	const formRef = ref()
	const formData = ref(uni.$xeu.clone(store.getters.userInfo, true))

  const avatarLoading = ref(false)

	const rules = reactive({
		phone: {
			rules: [{
				pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
				errorMessage: '请填写符合要求的11位手机号'
			}]
		},
		email: {
			rules: [{
				pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
				errorMessage: '请填写正确的邮箱号',
			}, ]
		},
	})
	// 性别
	const genderOptions = uni.$snowy.tool.dictList('GENDER')

  // 选择头像
  const chooseAvatar = () => {
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'], // 压缩图片
      sourceType: ['album', 'camera'], // 相册和相机
      success: (res) => {
        console.log('选择图片成功', res)
        const tempFilePath = res.tempFilePaths[0]
        uploadAvatar(tempFilePath)
      },
      fail: (err) => {
        console.error('选择图片失败:', err)
        uni.$snowy.modal.msgError('选择图片失败')
      }
    })
  }

  // 上传头像
  const uploadAvatar = (data) => {
    uni.showLoading({
      title: '上传中...'
    })
    // 转换为file类型
    const result = pathToFile(data)
    userCenterApi.userUpdateAvatar(data).then((res) => {
      console.log(res)
    }).catch((err) => {
      console.log("userCenterApi.userUpdateAvatar fail: ", err)
    })


  }

  const pathToFile = (filePath) => {
    // #ifdef H5 || MP-WEIXIN
    uni.getFileSystemManager().readFile({
		  filePath,
		  success: (res) => {
			  const fileName = getFileName(filePath)
        const file = new File([res.data], fileName, {type: 'image/jpeg', lastModified: Date.now() })
        return file
		  },
      fail: (err) => {
        console.error("转换File类型失败", err)
      }
	  })
    // #endif

    // #ifdef APP-PLUS

    // #endif
  }

  const getFileName = (path) => {
    return path.split('/').pop().split('?')[0]+Date.now()
  }

	// 提交
	const submit = () => {
		formRef.value.validate().then(res => {
			userCenterApi.userUpdateUserInfo(formData.value).then(data => {
				// 更新缓存 storage是store的基础实现类
				store.commit('SET_userInfo', formData.value)
				uni.$snowy.modal.showToast('修改成功')
				uni.navigateBack({
					delta: 1
				})
			})
		})
	}
</script>
<style lang="scss" scoped>
.avatar-container {
  margin: 20rpx 0;
  display: flex;
  justify-content: center;
  align-items: center;

  .avatar-wrapper {
    position: relative;
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    overflow: hidden;
    border: 2rpx solid #eee;

    .avatar-image {
      width: 100%;
      height: 100%;
    }

    .avatar-mask {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.5);
      opacity: 0;
      transition: 0.3s;

      &:active {
        opacity: 1; // 移动端适配点击态
      }
    }

    &:active .avatar-mask {
      opacity: 1;
    }
    
    .avatar-text {
      font-size: 24rpx;
      color: #fff;
      margin-top: 10rpx;
    }
  }
}
</style>